package com.vehiclesecure.controller;

import com.vehiclesecure.model.User;
import com.vehiclesecure.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser() {
        String email = SecurityContextHolder.getContext().getAuthentication().getName();
        Optional<User> user = userService.findByEmail(email);
        
        if (user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/me/vehicle")
    public ResponseEntity<?> bindVehicle(@RequestBody Map<String, String> vehicleData) {
        String email = SecurityContextHolder.getContext().getAuthentication().getName();
        String vehicleId = vehicleData.get("vehicleId");
        
        if (vehicleId == null || vehicleId.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "车辆ID不能为空"));
        }
        
        try {
            User user = userService.bindVehicleToUser(email, vehicleId);
            return ResponseEntity.ok(Map.of(
                "message", "车辆绑定成功",
                "user", user
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @DeleteMapping("/me/vehicle")
    public ResponseEntity<?> unbindVehicle() {
        String email = SecurityContextHolder.getContext().getAuthentication().getName();
        
        try {
            User user = userService.unbindVehicleFromUser(email);
            return ResponseEntity.ok(Map.of(
                "message", "车辆解绑成功",
                "user", user
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/admin/all")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getAllUsers() {
        return ResponseEntity.ok(userService.findAllUsers());
    }

    @PutMapping("/admin/{userId}/role")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateUserRole(@PathVariable String userId, @RequestBody Map<String, String> roleData) {
        String newRole = roleData.get("role");
        
        if (newRole == null || (!newRole.equals("USER") && !newRole.equals("ADMIN"))) {
            return ResponseEntity.badRequest().body(Map.of("error", "无效的角色"));
        }
        
        try {
            User user = userService.updateUserRole(userId, newRole);
            return ResponseEntity.ok(Map.of(
                "message", "用户角色更新成功",
                "user", user
            ));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }
}